package com.klz.iblog.securityHandler;


import com.alibaba.fastjson.JSON;
import com.klz.iblog.common.Result;
import com.klz.iblog.common.ResultCodeEnum;
import com.klz.iblog.pojo.SelfUserDetails;
import com.klz.iblog.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录成功时返回给前端的数据
 */
@Component
@Slf4j
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
    SelfUserDetails userDetails = (SelfUserDetails) authentication.getPrincipal();

    String jwtToken = JwtTokenUtil.generateToken(userDetails.getUsername(), 1500);

    httpServletResponse.getWriter().write(JSON.toJSONString(Result.result(ResultCodeEnum.RESULT_CODE_USER_LOGIN_SUCCESS,jwtToken,true)));
}
}
